package com.aplink.dellcommercial.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentActivity;

import com.aplink.dellcommercial.R;
import com.aplink.dellcommercial.database.DellDataTable;
import com.aplink.dellcommercial.webservices.DataResult;
import com.aplink.dellcommercial.webservices.Methods;
import com.aplink.dellcommercial.webservices.WebServiceHelper;
import com.aplink.generic.GenericFragment;
import com.aplink.generic.constant.HandlerConstant;
import com.aplink.generic.handler.IHandleMessage;
import com.aplink.generic.pojo.GenericObject;
import com.aplink.generic.pojo.controlspec.ControlSpec;

public class FetchUserProfileFragment extends GenericFragment implements
        IHandleMessage {
    private void handleDataResult( DataResult dataResult ) {
        if ( dataResult.getMethodName().equals( Methods.GET_CUSTOMER_INFO ) ) {
            if ( dataResult.getData() != null ) {
                final GenericObject genericObject = (GenericObject) dataResult
                        .getData();
                this.storeUserProfile( genericObject );
            }
        }
    }

    private void storeUserProfile( GenericObject genericObject ) {
        final long succeed = insertCommand().insertOrUpdate( genericObject,
                this.getObjPropCol() );
        Intent data = new Intent();
        if ( succeed != - 1 ) {
            data.putExtra( "FETCH_USER_RESULT", FragmentActivity.RESULT_OK );
        } else {
            data.putExtra( "FETCH_USER_RESULT", FragmentActivity.RESULT_CANCELED );
        }
        getActivity().setResult( LoginFragment.FETCH_USER_PROFILE_RESULT_CODE,
                data );
        this.finishActivity();
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState ) {
        super.onActivityCreated( savedInstanceState );
        this.initData();
        this.getHandler().setHandleMessage( this );
        WebServiceHelper.getInstance().getUserProfiles( getActivity(),
                this.getHandler(), this.getObjPropList() );
    }

    @Override
    public void onHandleMessage( Message msg ) {
        if ( msg.what == HandlerConstant.HTTP_TASK_RESULT ) {
            final DataResult result = (DataResult) msg.obj;
            this.handleDataResult( result );
        }
    }

    @Override
    protected void onHandleControlClickEvent( ControlSpec controlSpec ) {

    }

    @Override
    public int getContentView() {
        return NONE;
    }

    @Override
    public int getFormDesign() {
        return NONE;
    }

    @Override
    public int getContentData() {
        return R.raw.content_data_get_user_profiles;
    }

    @Override
    public String getTable() {
        return DellDataTable.UserProfile.TABLE_NAME;
    }
}
